package framework;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Framework class for collisions
 * 
 * @author Michael Deng
 * 
 */
public abstract class Collision {

    private Map<String, List<Sprite>> mySprites;
    private Level myLevel;

    /**
     * Initializes the collision
     * 
     * @param spriteList list of sprites held in the level
     * @param l pointer to the level
     */
    public void initialize (Map<String, List<Sprite>> spriteList, Level l) {
        mySprites = spriteList;
        myLevel = l;
    }

    /**
     * Allows the collision to update
     */
    public abstract void update ();

    /**
     * This method executes the action of the collision.
     * The two sprites affected by the collision are passed
     * in as arguments.
     * 
     * @param a first sprite
     * @param b second sprite
     */
    protected abstract void action (Sprite a, Sprite b);

    /**
     * This method executes certain actions if no collision
     * occurs between Sprite a and Sprite b.
     * 
     * @param a first Sprite
     * @param b second Sprite
     */
    protected void noCollisionAction (Sprite s) {

    }

    /**
     * Searches for and handles collisions
     * 
     * @param sprite1 first sprite
     * @param sprite2 second sprite
     */
    public void findAndHandleCollisions (String sprite1, String sprite2) {
        try {
            boolean noCollision = true;
            for (Sprite s : mySprites.get(sprite1)) {
                for (Sprite t : mySprites.get(sprite2)) {
                    if (checkCollision(s, t)) {
                        action(s, t);
                        noCollision = false;
                    }
                }
                if (noCollision) {
                    noCollisionAction(s);
                    noCollision = true;
                }
            }
        }
        catch (NullPointerException e) {
            // one of the lists of sprites is empty
        }
    }

    protected boolean checkCollision (Sprite a, Sprite b) {
        return a.getBounds().intersects(b.getBounds());
    }

    /**
     * 
     * @return the level that created this collision
     */
    public Level getMyLevel () {
        return myLevel;
    }

    protected Map<String, List<Sprite>> getMySprites () {
        return new HashMap<String, List<Sprite>>(mySprites);
    }
}
